<template>
  <el-dialog class="personInfo" v-model="showPersonInfo" title="用户基本信息" width="500px" center>
    <div style="text-align: center;padding-bottom: 25px;">
      <el-image :src="personInfo.avatarUrl" style="width: 100px;height: 100px;border-radius: 50px;" lazy>
        <template #error>
          <img src="/static/avatar.png" style="width: 100px;height: 100px;border-radius: 50px;" >
        </template>
        <template #placeholder>
          <img src="/static/avatar.png" style="width: 100px;height: 100px;border-radius: 50px;" >
        </template>
      </el-image>
    </div>
    <el-form ref="refPersonForm" :model="personInfo"  :rules="verifyRules" label-width="60px">
      <div class="personForm">
        <el-form-item prop="username" label="姓名">
          <el-input
              ref="username"
              v-model="personInfo.username"
              placeholder="姓名"
              name="username"
              type="text"
              auto-complete="on"></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input
              ref="nickname"
              v-model="personInfo.nickname"
              placeholder="昵称"
              name="nickname"
              type="text"
              auto-complete="on"></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-select v-model="personInfo.sex" class="m-2" placeholder="性别" style="width: 100%">
            <el-option
                v-for="item in sexOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="userphone" label="座机">
          <el-input
              ref="userphone"
              v-model="personInfo.userphone"
              placeholder="座机"
              name="userphone"
              type="text"
              auto-complete="on"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input
              ref="email"
              v-model="personInfo.email"
              placeholder="邮箱"
              name="email"
              type="text"
              auto-complete="on"></el-input>
        </el-form-item>
        <el-form-item prop="departmentId" label="部门">
          <el-tree-select v-model="personInfo.departmentId"
                          :data="deptTree"
                          :props="defaultProps"
                          check-strictly
                          :render-after-expand="false"
                          placeholder="请选择部门" style="width: 100%" />
        </el-form-item>
        <el-form-item prop="roles" label="角色">
          <el-select v-model="personInfo.roles" class="m-2" placeholder="请选择角色" style="width: 100%">
            <el-option
                v-for="item in rolesOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="orderNum" label="排序">
          <el-input-number v-model="personInfo.orderNum" :min="0" :max="1000" style="width: 100%"/>
        </el-form-item>
      </div>
      <el-button :loading="loading" type="primary" style="width:100%;margin-top:20px;"
                 @click.prevent="handleUpdate(refPersonForm)">保存修改</el-button>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import {onMounted, reactive, ref} from "vue";
import {useConfigStore} from "@/store/config";
import {storeToRefs} from "pinia";
import {IUser} from "@/iwb/IUser";
import {FormInstance, FormRules} from "element-plus";
import {validContactNumber} from "@/utils/validate";
import {getDepartment} from "@/api/config";
import {IDept} from "@/iwb/IConfig";
import {useUserStore} from "@/store/user";

export default {
  name: "PersonInfo",
  setup() {
    const loading = ref(false);
    const useConfig = useConfigStore()
    const {showPersonInfo, personInfo}  = storeToRefs(useConfig)

    const refPersonForm = ref<FormInstance>();
    personInfo.value.orderNum = 0;
    personInfo.value.sex = 0;
    personInfo.value.roles = 'ROLE_USER';

    const validateContact = (rule: any, value: string, callback: any) => {
      if (!validContactNumber(value) || value.length !== 11) {
        callback(new Error('请输入正确的座机号'))
      }  else {
        callback();
      }
    };
    const validateUsername = (rule: any, value: string, callback: any) => {
      const zg = /^\w+$/;
      if (zg.test(value)) {
        callback();
      } else {
        callback(new Error('请输入数字和字母组合的用户名'));
      }
    }

    const verifyRules = reactive<FormRules>({
      username: [{required: true, trigger: 'blur', validator: validateUsername}],
      nickname: [{required: true, trigger: 'blur', message: '请输入昵称'}],
      //userphone: [{required: true, trigger: 'blur', validator: validateContact}],
      departmentId: [{required: true, trigger: 'blur', message: '请选择部门'}],
      orderNum: [{required: true, trigger: 'blur', message: '请设置排序'}]
    })

    const defaultProps = ref({
      children: 'children',
      label: 'name',
      value: 'id'
    })
    const sexOptions = ref([{value: 0, label: '男'},{value: 1, label: '女'}]);
    const deptTree = ref([] as Array<IDept>);
    const rolesOptions = ref([{value: "ROLE_USER,ROLE_CENSOR,ROLE_ADMIN", label:'管理员'}, {value: "ROLE_USER,ROLE_CENSOR", label:'审核用户'}, {value: 'ROLE_USER', label: '普通用户'}])

    const reloadDeptTree = () => {
      loading.value = true;
      getDepartment().then(res => {
        deptTree.value = res.data;
        loading.value = false;
      }).catch(error => {
        console.error(error);
        loading.value = false;
      })
    }

    onMounted(() => {
      reloadDeptTree();
    })

    const handleUpdate = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      const userStore = useUserStore();
      loading.value = true;
      formEl.validate((valid: boolean, fields) => {
        loading.value = false;
        showPersonInfo.value = false;
        userStore.updateUser(personInfo.value);
      }).catch(erro=>{
        console.error(erro);
        loading.value = false;
      });
    }

    return {
      loading,
      showPersonInfo,
      personInfo,
      refPersonForm,
      verifyRules,
      defaultProps,
      sexOptions,
      deptTree,
      rolesOptions,
      reloadDeptTree,
      handleUpdate
    }
  }
}
</script>

<style scoped lang="scss">
  .personInfo {
    display: flex;
    align-items: center;
    flex-direction: column;
  }

  .personForm {
    margin: 10px;

    :deep(.personForm) {
      .el-select {
        width: 100%;
      }
    }
  }

  .dialog-footer button:first-child {
    margin-right: 10px;
  }
</style>